<!--
 * @Author: your name
 * @Date: 2025-03-06 10:42:21
 * @LastEditors: your name
 * @LastEditTime: 2025-06-12 11:28:45
 * @Description: 
 * @FilePath: \RuoYi-Vue3\src\views\login.vue
-->
<template>
  <div class="login-container">
    <div class="login">
      <div class="login_left" />
      <div class="login_right">
        <div class="title-container">
          <h3 class="title">{{ title || '后台管理系统'}}</h3>
        </div>
        <el-form ref="loginRef" :model="loginForm" v-loading="formLoading" :rules="loginRules" class="login-form">
          <el-form-item prop="username">
            <el-input maxlength="10" v-model.trim="loginForm.username" type="number" size="large" auto-complete="off"
              clearable placeholder="账号" @input="onInput">
              <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-form-item>
          <div class="login-select" v-show="isShowSelect">
            <el-select v-model="value" placeholder="无登录系统" size="large" style="width: 260px" @change="changeValue" >
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-select v-model="value2" placeholder="无用户角色" size="large"  style="width: 160px">
              <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <el-form-item prop="password">
            <el-input v-model.trim="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码"
              show-password @keyup.enter="handleLogin">
              <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input v-model.trim="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%"
              @keyup.enter="handleLogin">
              <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
            </el-input>
            <div class="login-code">
              <!-- <img :src="codeUrl" @click="getCode" class="login-code-img"/> -->
              <img :src="imgUrl" @click="getCode" class="login-code-img" />
            </div>
          </el-form-item>
          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
          <el-form-item style="width:100%;">
            <el-button :loading="loading" size="large" :disabled="isDisabled" type="primary"
              style="width: 100%; margin-top: 30px;height:50px;line-height: 50px;font-size:16px;"
              @click.prevent="handleLogin">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div style="float: right;" v-if="register">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!--  底部  -->
      <!-- <div class="el-login-footer">
        <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
      </div> -->
    </div>
  </div>
</template>

<script setup>
import { ElNotification , ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { getCodeImg , GetIndentityMark ,Login_Velocity , GetTenantSystem , GetRoleSystem} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import { set } from 'nprogress';
const imgUrl = ref(null)
const IndentityMark = ref(null)
const isShowSelect = ref(false)
const formLoading = ref(false)
const value = ref('')
const value2 = ref('')
const options = ref([])
const options2 = ref([])
const title = ref(null)

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: ""
});
// 自定义校验函数，验证是否为 11 位数字
const validateUsername = (rule, value, callback) => {
  const reg = /^\d{11}$/;
  if (!reg.test(value)) {
    callback(new Error('请输入正确的账号'));
  } else {
    callback();
  }
};

const loginRules = {
  username: [{ validator: validateUsername, trigger: "blur" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);
// 按钮计算属性
const isDisabled = computed(() => {
  let flag = loginForm.value.username==='' || loginForm.value.password==='' || value.value==='' || value2.value==='' || loginForm.value.code==='';
  return flag;
})

watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });


// 切换系统
function changeValue(val){
  value.value = val;
  title.value = options.value.find(item => item.value === val).label;
  GetRoleSystem(loginForm.value.username,val).then(res2 => {
    // 多个角色切换
      if(res2?.data){
        options2.value = res2.data.map(item => {
            return { value: item.id, label: item.name }
          })
          // 默认选择第一个角色
          value2.value = options2.value[0].value;

      }
  })

} 


//输入框限制
 function onInput(val) {  
  if (val.length > 11) {      
    loginForm.value.username = val.slice(0, 11);      
  }
  if(val.length==11){
    formLoading.value = true;
    GetTenantSystem(val).then(res => {
      // 是否有系统
        if(res?.data){
          options.value = res.data.map(item => {
            return { value: item.id, label: item.name }
          })
          // 默认选择第一个系统
          value.value = options.value[0].value;
          title.value = options.value.find(item => item.value === value.value).label;
          GetRoleSystem(val,res.data[0].id).then(res2 => {
          // 是否有角色
              if(res2?.data){
                options2.value = res2.data.map(item => {
                   return { value: item.id, label: item.name }
                 })
                 // 默认选择第一个角色
                 value2.value = options2.value[0].value;
              }
          })
          isShowSelect.value = true;
        }
     }).catch((err) => {
        options.value = [];
        options2.value = [];
        value.value = '';
        value2.value = '';
        isShowSelect.value = false;
     }).finally(() => {
        setTimeout(() => {
          formLoading.value = false;
        }, 200);
     })
  }
}
function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法（web方法）
      userStore.Login_Velocity({
          account: loginForm.value.username,
          passWord: loginForm.value.password,
          valiCode: loginForm.value.code,
          clientCode:IndentityMark.value,
          guidCode: "ERIC_2025",
          roleID: value2.value,
          tenantID: value.value
      }).then((res) => {
        ElMessage({
          message: res.message || '登录成功',
          type: 'success',
        })
        loading.value = false;
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({ path: "/", query: otherQueryParams });
      }).catch(() => {
        loading.value = false;

        // 重新获取验证码
        getCode();
      });
    }
  });
}

function getCode() {
  GetIndentityMark().then(res => {
    IndentityMark.value = res;
    imgUrl.value =  import.meta.env.VITE_APP_BASE_API +  `/api/Authorization/GetVerificateImgWithMark?IndentityMark=${res}&Length=4`
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
  onInput(loginForm.value.username);
}

getCode();
getCookie();
</script>

<style lang='scss' scoped>
.login-container {
  min-height: 100%;
  width: 100%;
  background: url("@/assets/images/bg.png") no-repeat;
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login {
  display: flex;
  align-items: center;
  width: 1060px;
  height: 700px;
  box-sizing: border-box;
  .login_left{
    width: 500px;
    height: 700px;
    background: url("@/assets/images/login.jpg") no-repeat;
    background-size: 100% 100%;
  }
  .login_right{
      width: 560px;
      height: 700px;
      background-color:#fff ;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

}
.login-form {
  width:560px;
  padding: 0 60px 0;
  .el-input {
    height: 60px;
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 55px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
    width: 160px;
  }
  .login-code-img {
    height: 55px;
    padding-left: 12px;
    box-sizing: border-box;
  }
}
.login-select{
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}
.title-container {
    // position: relative;
    .title {
      text-align: start;
      font-weight: bold;
      font-family: HarmonyOS Sans;
      font-size: 30px;
      line-height: 1.6;
      color: rgb(35, 47, 73);
      margin-top: 60px;
      margin-bottom: 40px;
    }
  }

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
::v-deep(.el-input__inner) {
  font-size: 18px;
}
::v-deep(.el-icon){
  font-size: 20px !important;
}
::v-deep(.svg-icon){
  width: 19px !important;
}
::v-deep(.el-checkbox__inner){
  width: 16px;
  height: 16px;
}
::v-deep(.el-checkbox__inner:after){
 left: 5px; 
}
::v-deep(.el-checkbox__label){
  font-size: 16px;
}
::v-deep(.el-select__wrapper){
  height: 55px !important;
}
</style>
<style>
input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
  margin: 0; 
}
input[type=number] {
  -moz-appearance: textfield; /* Firefox */
}
</style>
